import Vue from 'vue';
import Vuex from 'vuex';
import DZUtils from '@/utils/DZUtils';
// 假定我们有一个可以返回 Promise 的
// 通用 API（请忽略此 API 具体实现细节）
import {
  getFundInfo, getLoginUserInfo, getAdvertisement, getRecomendProdList, getFundDetailByCode, getIPOFunds, getFundColumn
} from '../api';

Vue.use(Vuex);

const isFront = process.env.VUE_APP_ENV === 'front';
const isClient = process.env.VUE_APP_ENV === 'client';

let store;
export default function createStore() {
  if ((isClient || isFront) && store) {
    return store;
  }
  store = new Vuex.Store({
    state: {
      isLoading: false, // 是否显示loading框
      loadingText: '加载中', // loading框文本
      refreshing: true, // 页面元素刷新状态
      requestCount: 0, // 请求数
      responseCount: 0, // 响应数
      title: '', // 页面标题
      pageBgWhite: false,
      statusBarHeight: 0, // app手机状态栏高度
      titleBarHeight: 0, // 页面标题高度、
      h5WrapHeight: 0, // 其他部分高度
      hasShare: false, // 是否已设置分享文案
      userInfo: {}, // 用户信息
      assetsInfo: {}, // 资产信息
      adList: [], // 首页广告banner
      recommendList: [], // 首页推荐产品
      redirect: {}, // 业务跳转后记录上一路由信息
      ipoFundList: [], // 首页首发基金
      // hotProductList: [], // 首页热门产品
    },
    actions: {
      async getAssetsInfo({ commit }, { cookie = '' } = {}) {
        const { returnCode, returnInfo, dataSet } = await getFundInfo({ cookie });
        if (returnCode === '0' && dataSet.length) {
          commit('setAssetsInfo', { assetsInfo: dataSet[0] });
        }
      },
      async getLoginUserInfo({ commit }, { isLogin, cookie = '' }) {
        let userInfo = { isLogin: false };
        const { returnCode, dataSet } = await getLoginUserInfo(isLogin, { cookie });
        if (returnCode === '0') {
          if (dataSet.length) {
            userInfo = { isLogin: true, ...dataSet[0] };
          }
        }
        commit('setUserInfo', userInfo);
      },
      // 首页广告
      async getAdvertisement({ commit }, { ctxLogger } = {}) {
        try {
          if (ctxLogger) {
            ctxLogger.info('server getAdvertisement start');
          }
          const { returnCode, returnInfo, dataSet } = await getAdvertisement();
          if (ctxLogger) {
            ctxLogger.info(`server getAdvertisement suc. returnCode: ${returnCode}, returnInfo: ${returnInfo}, dataSet: ${dataSet.length}`);
          }
          if (returnCode === '0' && dataSet.length) {
            commit('setAdList', { adList: dataSet });
          }
          return { returnCode, returnInfo };
        } catch (err) {
          if (ctxLogger) {
            ctxLogger.error(`server getAdvertisement err.`, err);
          }
        }
      },
      // 首页产品推荐轮播
      async getRecomendProdList({ commit }, { pageIndex, ctxLogger } = {}) {
        try {
          if (ctxLogger) {
            ctxLogger.info('server getRecomendProdList start');
          }
          const { returnCode, returnInfo, dataSet } = await getRecomendProdList(pageIndex);
          if (ctxLogger) {
            ctxLogger.info(`server getRecomendProdList suc. returnCode: ${returnCode}, returnInfo: ${returnInfo}, dataSet: ${dataSet.length}`);
          }
          if (returnCode === '0' && dataSet.length) {
            commit('setRecommendList', { recommendList: dataSet[0].recomendProdList });
          }
          return { returnCode, returnInfo };
        } catch (err) {
          if (ctxLogger) {
            ctxLogger.error(`server getRecomendProdList err.`, err);
          }
        }
      },
      // 基金详情页基金详情
      async getFundDetailByCode({ commit }, { prodCode }) {
        const { returnCode, returnInfo, dataSet } = await getFundDetailByCode(prodCode);
        if (returnCode === '0' && dataSet.length) {
          commit('setProdInfo', { prodInfo: dataSet[0] });
        }
        return { returnCode, returnInfo };
      },
      // 首页 首发基金
      async getIPOFunds({ commit }, { ctxLogger } = {}) {
        try {
          if (ctxLogger) {
            ctxLogger.info('server getIPOFunds start');
          }
          const { returnCode, returnInfo, dataSet } = await getIPOFunds();
          if (ctxLogger) {
            ctxLogger.info(`server getIPOFunds suc. returnCode: ${returnCode}, returnInfo: ${returnInfo}, dataSet: ${dataSet.length}`);
          }
          if (returnCode === '0' && dataSet.length) {
            commit('setIpoFundList', { ipoFundList: dataSet });
          }
          return { returnCode, returnInfo };
        } catch (err) {
          if (ctxLogger) {
            ctxLogger.error(`server getIPOFunds err.`, err);
          }
        }
      },
      // 首页 热门产品
      async getHotProducts({ commit }) {
        const { returnCode, returnInfo, dataSet } = await getFundColumn('index_col1');
        if (returnCode === '0' && dataSet.length) {
          commit('setHotProductList', { hotProductList: dataSet });
        }
        return { returnCode, returnInfo };
      },
    },
    mutations: {
      // 记录loading框显示隐藏状态
      setLoadingState(state, isLoading) {
        state.isLoading = isLoading;
      },
      // 设置loading框显示文字
      setLoadingText(state, loadingText) {
        state.loadingText = loadingText;
      },
      setRefreshingState(state, refreshing) {
        state.refreshing = refreshing;
      },
      // 请求数+1
      setRequestCount(state, payload) {
        state.requestCount += 1;
      },
      // 重置请求数
      resetRequestCount(state, payload) {
        state.requestCount = 0;
      },
      // 响应数+1
      setResponseCount(state, payload) {
        state.responseCount += 1;
      },
      // 重置响应数
      resetResponseCount(state, payload) {
        state.responseCount = 0;
      },
      setTitle(state, title) {
        state.title = title;
      },
      setPageBgWhite(state, pageBgWhite) {
        state.pageBgWhite = pageBgWhite;
      },
      setTitleBarHeight(state, titleBarHeight) {
        state.titleBarHeight = titleBarHeight;
      },
      setH5WrapHeight(state, h5WrapHeight) {
        state.h5WrapHeight = h5WrapHeight;
      },
      setStatusBarHeight(state, statusBarHeight) {
        state.statusBarHeight = statusBarHeight;
      },
      setUserInfo(state, userInfo) {
        state.userInfo = userInfo;
      },
      setAssetsInfo(state, { assetsInfo }) {
        state.assetsInfo = {
          ...assetsInfo
        };
      },
      setAdList(state, { adList }) {
        state.adList = [].concat(adList);
      },
      setRecommendList(state, { recommendList }) {
        state.recommendList = [].concat(recommendList);
      },
      // 业务跳转后记录上一路由信息
      setRedirect(state, redirect) {
        state.redirect = redirect;
        DZUtils.setStorage('redirect', redirect);
      },
      setProdInfo(state, { prodInfo }) {
        state.prodInfo = { ...prodInfo };
      },
      removeAd(state, ad) {
        state.adList = state.adList.filter(item => item.id != ad.id);
      },
      setIpoFundList(state, { ipoFundList }) {
        state.ipoFundList = [].concat(ipoFundList);
      },
      setHotProductList(state, { hotProductList }) {
        state.hotProductList = [].concat(hotProductList);
      },
    }
  });
  return store;
}
